package com.wk.controller;

import com.alibaba.fastjson.JSON;
import com.wk.common.Permission;
import com.wk.common.Permissions;
import com.wk.common.ReturnObject;
import com.wk.common.UserInfo;
import com.wk.domain.TblUserRecord;
import com.wk.service.TblUserRecordService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.List;

@RestController
public class LoginController {

    @Autowired
    private TblUserRecordService userRecordService;

    /**
     * 登录 将用户信息写入到session
     */
    @RequestMapping("/auth/login")
    public String login(String username, String password, HttpSession session) {
        TblUserRecord userRecord = userRecordService.login(username,password);
        userRecord.setToken(userRecord.getUserName());
        //用户数据写入到session
        session.setAttribute("userRecord",userRecord);
        return JSON.toJSONString(new ReturnObject(userRecord));
    }

    /**
     * 获取并解析session中的用户信息
     */
    @RequestMapping("/users/info")
    public String getInfo(HttpSession session){
        TblUserRecord userRecord = (TblUserRecord) session.getAttribute("userRecord");
        String[] split = userRecord.getTblRole().getRolePrivileges().split("-");

        //创建权限集合对象
        Permissions permissions = new Permissions();

        //向权限集合对象中添加具体的权限
        List<Permission> list = new ArrayList<>();

        for (String s : split) {
            list.add(new Permission(s));
        }

        permissions.setPermissions(list);
        UserInfo userInfo = new UserInfo(userRecord.getUserName(), permissions);
        return JSON.toJSONString(new ReturnObject(userInfo));
    }

    @RequestMapping("/auth/logout")
    public void logout(HttpSession session) {
        session.invalidate();
    }
}

